<template>
  <div class="timing">
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline queryFrom">
          <el-form-item label="任务名称">
            <el-input v-model="formInline.dataModelName" clearable placeholder="请输任务名称" />
          </el-form-item>
          <el-form-item>
            <el-button plain @click="getUserList"><Icon type="ios-search" />查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <!-- ykp/sjxf/index -->
        <el-button type="primary" @click="addUser('add')"><Icon type="md-add" />创建实时任务</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <ykhttb
      ref="httbRef"
      :btn-is-show="btnIsShow"
      :table-col="tabUserList"
      :table-data="tableUserData"
      width="180"
      @getDataDetileInfo="getDataDetileInfo"
      @sendData="sendData"
      @deleteSelectData="deleteSelectData"
      @refresh="getUserList"
    />
    <!-- 分页 -->
    <div style="text-align:right;margin-top:10px;">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      width="50%"
      :visible.sync="dialogTableVisible"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm autoClass">
        <!--  -->
        <el-form-item label="类型" prop="typeMq">
          <el-select v-model="ruleForm['typeMq']" :disabled="title=='修改'" clearable placeholder="请选择类型">
            <el-option label="kafka" value="kafka"></el-option>
            <el-option label="rabbitmq" value="rabbitmq"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="ruleForm['typeMq']!='kafka'?'路由任务名称':'主题任务名称'" prop="topicTaskName">
          <el-input v-model="ruleForm['topicTaskName']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="任务描述" prop="comments">
          <el-input v-model="ruleForm['comments']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item v-if="ruleForm['typeMq']=='kafka'" label="Broker" prop="clusterId">
          <el-select v-model="ruleForm.clusterId" @change="queryTremOptions(ruleForm.clusterId)" :disabled="disFlag" clearable placeholder="请选择Broker">
            <el-option
              v-for="(item,i) in options1"
              :key="i"
              :label="item.broker"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item  v-if="ruleForm['typeMq']=='rabbitmq'" label="Broker" prop="clusterId">
          <el-select v-model="ruleForm.clusterId" @change="queryRouterList(ruleForm.clusterId)" :disabled="disFlag" clearable placeholder="请选择Broker">
            <el-option
              v-for="(item,i) in BrokerOptions"
              :key="i"
              :label="item.clusterName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm['typeMq']=='kafka'" v-loading="pageloading1" label="主题" prop="topicName">
          <el-select v-model="ruleForm.topicName" :disabled="disFlag" clearable placeholder="请选择主题">
            <el-option
              v-for="(item,i) in options2"
              :key="i"
              :label="item.clusterName"
              :value="item.topicName"
            />
          </el-select>
        </el-form-item>
        <el-form-item  v-if="ruleForm['typeMq']=='rabbitmq'" label="路由" prop="topicName" v-loading="pageloading">
          <el-select v-model="ruleForm.topicName" :disabled="disFlag" clearable placeholder="请选择主题">
            <el-option
              v-for="(item,i) in topicNameoptions"
              :key="i"
              :label="item.routingName"
              :value="item.routingName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="指定结构" prop="structure">
          <el-input v-model="ruleForm['structure']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item v-if="ruleForm['typeMq']=='kafka'" label="分组ID" prop="groupId">
          <el-input v-model="ruleForm['groupId']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <!-- modelName -->
        <el-form-item label="数据模型" prop="modelId">
          <el-select v-model="ruleForm.modelId" @change="getFiledOptions(ruleForm.modelId)" :disabled="disFlag" clearable placeholder="请选择数据类型">
            <el-option
              v-for="(item,i) in options3"
              :key="i"
              :label="item.dataModelName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表名" prop="dataTable">
          <el-input v-model="ruleForm['dataTable']" :disabled="disFlag" clearable placeholder=""><template slot="prepend">tb_rt_</template></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <div style="padding: 10px 10px 0 0;width: 100%;max-height:220px;overflow-y: scroll;" >
          <div class="autoClass" style="margin-bottom: 10px;" v-for="(item,index) in gzListOptions" :key="index">
            <div class="autoClass" style="flex-wrap: nowrap;width: 47%;">
              <label style="width:140px;text-align: right;padding-right: 20px;line-height: 35px;">规则字段</label>
              <el-select v-model="item.ruleField" :disabled="disFlag" clearable placeholder="请选择规则字段">
                <el-option
                  v-for="(item,i) in options4"
                  :key="i"
                  :label="item.fieldName"
                  :value="item.fieldName"
                />
              </el-select>
            </div>
            <div class="autoClass" style="flex-wrap: nowrap;width: 47%;">
              <label style="width:140px;text-align: right;padding-right: 20px;line-height: 35px;">质量规则</label>
              <el-select v-model="item.quality" :disabled="disFlag" clearable placeholder="请选择质量规则">
                <el-option
                  v-for="(item,i) in options5"
                  :key="i"
                  :label="item.qualityRuleName"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div  style="width: 6;margin-left: 10px;">
              <el-button v-if="index==0" @click="addgzListOptions('add')" type="primary"><i style="font-size: 12px;" class="el-icon-circle-plus-outline" /></el-button>
              <el-button v-else @click="addgzListOptions(index)" type="danger"> <i style="font-size: 12px;" class="el-icon-remove-outline" /> </el-button>
            </div>
          </div>
        </div>
      </el-form>
      <div v-if="!disFlag" style="text-align: center;margin-top: 20px;">
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="resetForm('return')">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 列表查询
import {
  topicTaskpage,
  topicTaskdelete,
  topicTasksavaTopicTask,
  topicTaskupdateTopicTask,
  dataQualityrulegetList,
  clusterpage,
  dataModeldatagetList,
  topiclist,
} from '@/api/zt/index'
import request from '@/utils/request'
import experiment from '@/mixins/experiment'
import MiddleUtil from '@/utils/MiddleUtil'
export default {
  components: {},
  mixins: [experiment],
  data() {
    var validatePass = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('表名不能为空'));
        }
        const regex = /^tb_rt_/;
        if (!regex.test(value)) {
          callback(new Error('必须以tb_rt_开头'));
        } else {
          callback();
        }
      };
    return {
      pageloading:false,
      pageloading1:false,
      topicNameoptions:[],
      BrokerOptions:[],
      nsList:[],
      options1:[],
      options2:[],
      options3:[],
      options4:[],
      options5:[],
      gzListOptions:[
        {
          "ruleField":"",
          "quality":""
        }
      ],
      sendShow: false,
      width: '25%',
      btnIsShow: {
        operate: true,
        detile: false,
        del: true
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      title: '新增',
      rules: {
        typeMq: [
            { required: true, message: '请选择类型', trigger: 'change' }
        ],
        topicTaskName: [
            { required: true, message: '请输入主题任务名称', trigger: 'change' }
        ],
        clusterId: [
            { required: true, message: '请选择Broker', trigger: 'change' }
        ],
        topicName: [
            { required: true, message: '请选择主题', trigger: 'change' }
        ],
        groupId: [
            { required: true, message: '请输入分组ID', trigger: 'change' }
        ],
        dataTable: [
            // { required: true,validator: validatePass, trigger: 'change' }
            { required: true,message: '请输入表名', trigger: 'change' }

        ],
        modelId: [
            { required: true, message: '请选择数据模型', trigger: 'change' }
        ]
      },
      ruleForm: {
        "typeMq":'kafka',
        "qualityRule":[],
        "clusterId": 0,
        "clustername": "",
        "comments": "",
        "createTime": "",
        "dataTable": "",
        "groupId": "",
        "id": 0,
        "modelId": 0,
        "modelName": "",
        "spare1": "",
        "spare2": "",
        "status": 0,
        "structure": "",
        "threadId": 0,
        "topicName": "",
        "topicTaskName":"",
        "updateTime": ""
      },
      userId: '',
      formInline: {
        'dataModelName': '',
        'dataModelTypeId': ''
      },
      addParms: [],
      dialogTableVisible: false,
      addParms2: [],
      tableUserData: [],
      tabUserList: [
        {
          key: 'topicTaskName',
          title: '任务名称'
        },
        {
          key: 'clustername',
          title: '集群名称'
        },
        {
          key: 'topicName',
          title: '主题名称'
        },
        {
          key: 'createTime',
          title: '创建时间'
        }
      ],
      total: 0,
      size: 10,
      page: 1
    }
  },
  created() {

  },
  mounted() {

    this.$nextTick(() => {

        request({
            url: '/ht-datacenter/rabbit/getRabbitMqList',
            method: 'post',
            data:{
                "page":1,
                "limit":1000
            }
          }).then(res => {
            if (res.code == 200) {
              this.BrokerOptions = res.data.records
            } else {}
          })



      this.getUserList()
      clusterpage({
        'pageIndex':1,
        'pageSize':1000,
        'sk_like_clusterName':''
      }).then(res => {
        this.options1 = res.data.records
      })


      dataModeldatagetList({
        'pageIndex': 1,
        'dataModelName': '',
        'dataModelTypeId': '',
        'pageSize': 1000
      }).then(res => {
        this.options3 = res.data.records
      })

      dataQualityrulegetList({
        'pageIndex':1,
        'pageSize':1000,
        'qualityRuleName':''
      }).then(res => {
        this.options5 = res.data.records
      })
    })
  },
  methods: {
      queryRouterList(v) {
        this.pageloading = true
        request({
            url: '/ht-datacenter/rabbit/getRoutingKeyInfo',
            method: 'post',
            data:{
            "clusterId":v,
            "page":1,
            "limit":1000
            }
        }).then(res => {
            if (res.code == 200) {
              this.topicNameoptions = res.data.resultList
            } else {
              this.$notify.error({
                  title: '错误',
                  message: res.msg
              })
            }
        }).finally(()=>{
          this.pageloading = false
          MiddleUtil.$on('requestError', () => {
            this.pageloading = false
          })
        })
      },
    addgzListOptions(v){
      if(v=='add'){
        this.gzListOptions.push(
          {
            "ruleField":"",
            "quality":""
          }
        )
      }else{
        this.gzListOptions.splice(v,1)
      }
    },
    getFiledOptions(v){
      if(v.length==0){
        this.options4 = []
      }
      this.options3.forEach((item,index)=>{
        if(item.id==this.ruleForm.modelId){
          this.ruleForm.modelName = item.dataModelName
        }
        if(item.id==v){
          this.options4 = item.fields
        }
      })
    },
    queryTremOptions(id){
      this.options1.forEach((item,index)=>{
        if(item.id==this.ruleForm.clusterId){
          this.ruleForm.clustername = item.clusterName
        }
      })
      this.pageloading1 = true
      topiclist({
        'cluster':id
      }).then(res => {
        this.options2 = res.data
      }).finally(()=>{
        this.pageloading1 = false
        MiddleUtil.$on('requestError', () => {
          this.pageloading1 = false
        })
      })
    },
    deleteSelectData(v) {
      topicTaskdelete({ id: [v.id] }).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.$notify.error({
            title: '错误',
            message: res.msg
          })
        }
      })
    },
    sendData() {
      this.dia2logTableVisible2 = true
    },
    verifyRequired(){
      let flag =true;
      this.nsList = []
      if(this.gzListOptions.length==1){
        if(!this.gzListOptions[0].quality && !this.gzListOptions[0].ruleField){
          this.ruleForm.qualityRule = null
          flag = true
        }else if(this.gzListOptions[0].quality && this.gzListOptions[0].ruleField){
          this.ruleForm.qualityRule = JSON.stringify(this.gzListOptions)
          flag = true
        }else{
          flag = false
          this.$message.error(`请把第1条规则信息填写完整`)
        }
      }else{
        this.gzListOptions.forEach((item,index)=>{
          if((!item.quality&&item.ruleField)||(item.quality&&!item.ruleField)){
            flag = false
            this.$message.error(`请把第${index+1}条规则信息填写完整`)
          }else if(item.quality&&item.ruleField){
            this.nsList.push({
              quality:item.quality,
              ruleField:item.ruleField
            })
          }
        })
        this.ruleForm.qualityRule = JSON.stringify(this.nsList)
      }
      return flag;
    },

    commitFromData() {
      this.title == '新增'?delete this.ruleForm.id:''
      if(!this.verifyRequired()){
        // 验证规则字段必填项start
        return
      }
      let params = JSON.parse(JSON.stringify(this.ruleForm))

      params.dataTable = 'tb_rt_'+this.ruleForm.dataTable
      if (params.hasOwnProperty('id')) {
          topicTaskupdateTopicTask(params).then(res => {
            if (res.code == 200) {
              this.$message.success('修改成功')
              this.getUserList()
            } else {
              this.errorDialog(res.msg)
            }
          })
      } else {
        if(this.ruleForm['typeMq']=='kafka'){
          topicTasksavaTopicTask(params).then(res => {
            if (res.code == 200) {
              this.$message.success('新增成功')
              this.getUserList()
            } else {
              this.errorDialog(res.msg)
            }
          })
        }else{
          this.addrabbitFun(params)
        }
      }
    },
    addrabbitFun(params){
      request({
          url: '/ht-datacenter/rabbit/createRabbitMqTask',
          method: 'post',
          data:params
        }).then(res => {
          if (res.code == 200) {
              this.$message.success('新增成功')
              this.getUserList()
            } else {
              this.errorDialog(res.msg)
            }
        })
    },
    handleSizeChange(v) {
      this.page = 1
      this.size = v
      this.getUserList()
    },
    handleCurrentChange(v) {
      this.page = v
      this.getUserList()
    },

    // 获取用户列表
    getUserList() {
      this.dialogTableVisible = false
      this.$refs.httbRef.isShowLoading(true)

      topicTaskpage({
        'pageIndex': this.page,
        'or_orderby_createTime':'dsc',
        'sk_like_topicTaskName': this.formInline.dataModelName,
        'pageSize': this.size
      }).then(res => {
        this.tableUserData = res.data.records
        this.total = res.data.total
        this.$refs.httbRef.isShowLoading(false)

      })
    }
  }
}
</script>

<style lang="scss" scoped>
      >>>.jsoneditor-poweredBy {
        display: none !important;
      }

      .addPs{
        display: flex;
        flex-direction: row;
        margin-bottom: 10px;
        >div{
          width:50%
        }
        span{
          display: inline-block;
          width: 10%;
        }
      }
      .autoClass{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
      }
      .autoClass .el-form-item{
        width:49%;
      }
      .addcs{
        display: flex;
        flex-direction: row;
        margin-bottom: 10px;
      }
      .addcs2 .el-select {
        display: inline-block;
        width: 240px;
      }
      .autoInput{
        display: inline-block;
        width: 70%;
      }
      .infoTitle{
        border-bottom:1px solid #e5e5e5;
        margin-bottom: 30px;
        position: relative;
      }
      .infoTitle>span{
        position: absolute;
        left: 20px;
        background: #fff;
        width:80px;
        top:-15px;
        height:30px;
        text-align: center;
        line-height: 30px;
      }
        .el-select{
           width:100%;
        }
        .timing{
          background:#fff;
          padding:20px;
        }
      </style>
